package com.stud.common.core.domain.echarts;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * K: 数据字典 key 的类型
 * T: 数据类型
 *
 * @author Stud
 * @date 2023-12-13 9:08
 */
@Data
@Schema(description = "echarts柱状图折线图统一响应类")
@AllArgsConstructor
@NoArgsConstructor
public class Echarts<K, T> implements Serializable {
    @Schema(description = "字典")
    private Map<K, String> dict = new HashMap<>();

    @Schema(description = "X轴")
    private List<String> xAxis = new ArrayList<>();

    @Schema(description = "柱/折线")
    private List<EchartsData<K, T>> series = new ArrayList<>();

    public void addSeries(EchartsData<K, T> data) {
        this.series.add(data);
    }

    public void addXAxis(String x) {
        this.xAxis.add(x);
    }

    public void setDict(Map<K, String> dict) {
        setDict(dict, true);
    }

    /**
     * @param dict               字典
     * @param solveDuplicateName 是否处理重名
     */
    public void setDict(Map<K, String> dict, boolean solveDuplicateName) {
        if (!solveDuplicateName) {
            this.dict = dict;
            return;
        }

        Map<String, Integer> nameMap = new HashMap<>();
        List<K> list = new ArrayList<>();
        dict.forEach((k, v) -> {
            this.dict.put(k, v);
            list.add(k);
            nameMap.put(v, nameMap.getOrDefault(v, 0) + 1);
        });

        for (K k : list) {
            String v = this.dict.get(k);
            if (nameMap.get(v) != 1) {
                this.dict.put(k, v + "-" + k);
            }
        }
    }
}
